<template>
  <div class="app-container">
    <el-container class="dcs-main-container" >
      <el-aside class="real-aside" width="300px" v-if="device!=='mobile'">
        <div style="margin-bottom: 10px"></div>
        <el-row style="height: 40px">
          <el-input prefix-icon="el-icon-search" style="width:100%" v-model="apvQuery.name" placeholder="关键字"></el-input>
        </el-row>
        <div style="margin-bottom: 20px"></div>
        <el-row>
          <el-tree v-loading="treeLoading" class="dcs-left-tree"  ref="OrganizeTreeRef" :check-strictly="true" :filter-node-method="filterNode" :data="OrganizeTree"
                       :props="treeProps" node-key="id" default-expand-all  show-checkbox :close-on-click-modal="false" @check="treeCheck" @node-click="nodeCheck">
            <span slot-scope="{ node, data }" class="custom-tree-node">
              <span>
                <span v-if="data.type==OrgnizeType.ANCESTOR" class="mgl-10"><span class="tenant-title">{{ data.name }}</span></span>
                <span v-else-if="data.type==OrgnizeType.FACTORY" class="mgl-10"><span class="company-title">{{ data.name }}</span><el-tag v-if="data.sub_title" type="info" size="mini">({{ data.sub_title }})</el-tag></span>
                <span v-else-if="data.type==OrgnizeType.DEPARTENT" class="mgl-10"><span class="department-title">{{ data.name }}</span></span>
              </span>
            </span>
          </el-tree>
        </el-row>
      </el-aside>
      <el-container>
        <el-header class="date-search-header" :height="device==='mobile'?'90px':'60px'">
          <el-select v-model="apvQuery.orgnization_id" placeholder="请选择组织" @change="orgnizeChange" v-if="device==='mobile'">
            <el-option v-for="(item,index) in OrganizeTree[0].children" :key="index" :label="item.name" :value="item.id"  />
          </el-select>
          <div class="date-picker">
              <el-date-picker
              v-model="apvQuery.dtrange"
              :style="{width:device==='mobile'?'70%':'40%'}"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="yyyy-MM-dd"
              :clearable="false"
              value-format="yyyy-MM-dd"></el-date-picker>
              <el-button style="margin-left: 10px" type="primary" @click="fetchTable">筛选</el-button>
            </div>
        </el-header>
        <el-main>
          <el-table :data="reportData"
                    style="width: 100%"
                    :border="true"
                    v-loading="tableLoading"
                    element-loading-text="统计生成中..."
                    element-loading-spinner="el-icon-loading">
            <el-table-column v-for="(col,idx) in reportCols" :key="idx" :prop="col.prop" :label="col.label" :type="col.type" :width="col.width" :fixed="col.fixed" align="center">
              <template slot-scope="scope">
                <el-tag type="success" size="mini" v-if="typeof scope.row[col.prop]!=='string'&&scope.row[col.prop]">已填写</el-tag>
                <el-tag type="danger" size="mini" v-else-if="!scope.row[col.prop]">未填写</el-tag>
                <span v-else>{{scope.row[col.prop]}}</span>
              </template>
            </el-table-column>
          </el-table>
        </el-main>
      </el-container>
    </el-container>
  </div>
</template>

<script>
  import {mapGetters} from 'vuex'
  import homeApi from '@/api/article'
  import debounce from 'lodash/debounce'
  import { confirm,OrgnizeType } from '@/utils/constants'
  import {parseTime} from "@/utils"
  const sevenDaysAgo = parseTime(new Date().getTime()-24*3600*1000*7,'{y}-{m}-{d}')
  const today = parseTime(new Date(),'{y}-{m}-{d}')
  export default {
    name: 'normal-enter-count',
    computed:{
      ...mapGetters([
        'device'
      ])
    },
    data(){
      return {
        apvQuery:{
          dtrange:[sevenDaysAgo,today],
          orgnization_id:null
        },
        treeLoading:false,
        tableLoading:false,
        OrgnizeType,
        OrganizeTree: [{children:[]}],
        reportData:[],
        reportCols:[],
        treeProps: {
          label: 'name',
          children: 'children'
        }
      }
    },
    watch: {
      'apvQuery.name': debounce(function(val) {
        this.$refs.OrganizeTreeRef.filter(val)
      }, 600)
    },
    created() {
      this.fetchTree()
    },
    methods:{
      async fetchTree() {
        this.treeLoading = true
        this.OrganizeTree = await this.$store.dispatch('user/ownedOrgnizes')
        this.treeDefaultCheck()
        this.treeLoading = false
      },
      treeDefaultCheck(){
        const firstNode = this.OrganizeTree[0].children[0]
        if (this.device==='mobile'){
          this.apvQuery.orgnization_id = firstNode.id
          this.fetchTable()
          return
        }
        this.$nextTick(()=>{
          this.$refs['OrganizeTreeRef'].setChecked(firstNode.id, true, false)
          this.treeCheck(firstNode)
        })
      },
      filterNode(value, data) {
        if (!value) return true
        return data.name.indexOf(value) !== -1
      },
      treeCheck(row,data){
        const needClosed = this.$refs.OrganizeTreeRef.getCheckedKeys().filter(ck=>ck!=row.id)
        needClosed.forEach(ck=> {
          this.$refs.OrganizeTreeRef.setChecked(ck, false, false)
        })
        const currentOrgIds = this.$refs.OrganizeTreeRef.getCheckedKeys()
        this.apvQuery.orgnization_id = null
        if (currentOrgIds.length)
          this.apvQuery.orgnization_id = currentOrgIds[0]
        if (!this.apvQuery.orgnization_id){
          this.$message.warning("请选择组织!")
          return
        }
        this.fetchTable()
      },
      nodeCheck(row, node, el){
        this.$refs['OrganizeTreeRef'].setChecked(row.id, true, false)
        this.treeCheck(row)
      },
      fetchTable(){
        this.tableLoading=true
        const params = {
          start:this.apvQuery.dtrange[0],
          end:this.apvQuery.dtrange[1],
          orgnization_id:this.apvQuery.orgnization_id
        }
        homeApi.summaryDetail(params).then(res=>{
          const tableData = this.convertData(res.data)
          this.reportCols = tableData[0]
          setTimeout(()=>{
            this.reportData = tableData[1]
            this.tableLoading=false
          },200)
        })

      },
      convertData(dataList){
        let tbCols=[]
        let tbArr=[]
        dataList.header.forEach(hd=>{
          tbCols.push({
            prop:hd.en_name,
            label:hd.cn_name,
            children:[]
          })
        })
        for (let data of dataList.data){
          let tbEntity = {}
          for (let tag in data){
            tbEntity[tag] = data[tag]
          }
          tbArr.push(tbEntity)
        }
        return [tbCols,tbArr]
      },
      orgnizeChange(){
        this.fetchTable()
      }
    }

  }
</script>

<style lang="scss" scoped>
  @import 'src/styles/variables.scss';
  .tenant-title{
    font-weight: normal;
    color:$tenant-color;
  }
  .company-title{
    font-weight: lighter;
    color: $company-color;
    font-size: small;
    margin-right: 10px;
  }
  .department-title{
    font-weight: lighter;
    color: $department-color;
    font-size: small;
  }
  .app-container{
    padding: 0;

      .dcs-main-container{
        width: 100%;
        min-height: calc(100vh - 84px);
      }
      .real-aside{
        margin-bottom: 0;
        max-height:calc(100vh - 84px);
        overflow-y: auto;

        .el-tree{
          min-height: calc(100vh - 204px);
          padding-top: 10px;
          width: 100%;
          overflow-x: auto;
          overflow-y: hidden;
        }

        .el-tree>.el-tree-node{
          display: inline-block;
          min-width: 100%;
        }

    }
    .date-search-header{
      padding: 0 10px;
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: flex-start;

      .date-picker{
        width: 100%;
        margin-top: 10px;
      }
    }
    .tb-view{
      width: 100%;
    }


  }

</style>
